﻿using System;
using System.Collections.Generic;
using Ctef.Web.Extensions;
using Ctef.Web.Models;
using System.IO;
using System.Xml.Serialization;

namespace Ctef.Web.Repositories
{
    public class XmlDataRepository
    {
        private const string DefaultLocale = "en-us";
        private static XmlDataRepository instance;
        private static object sync = new object();

        private Dictionary<string, MainPage> localizedMainPages;

        private XmlDataRepository()
        {
        }

        public static XmlDataRepository Instance
        {
            get 
            {
                if (instance != null)
                {
                    return instance;                        
                }

                lock (sync)
                {
                    if (instance == null)
                    {
                        instance = new XmlDataRepository();
                    }

                }

                return instance;             
            }
        }

        public void InitializeMainPages(string path)
        {
            if (localizedMainPages != null)
            {
                return;
            }

            lock (sync)
            {
                if (localizedMainPages != null)
                {
                    return;
                }

                var files = new[] { "MainPage.xml", "MainPage.zh-cn.xml", "MainPage.zh-tw.xml" };
                localizedMainPages = new Dictionary<string, MainPage>();

                foreach (var file in files)
                {
                    using (var text = new FileStream(Path.Combine(path, file), FileMode.Open, FileAccess.Read))
                    {
                        var ser = new XmlSerializer(typeof(MainPage));
                        var mainPage = (MainPage)ser.Deserialize(text);
                        var locale = mainPage.Language.Trim().ToLowerInvariant();
                        localizedMainPages.Add(locale, mainPage);
                    }
                }                
            }
        }

        public MainPage GetMainPageByLocale(string locale)
        {
            if (string.IsNullOrEmpty(locale))
            {
                throw new ArgumentException("Invalide locale.");
            }
            
            locale = locale.Trim().ToLowerInvariant();
            var result = localizedMainPages.ContainsKey(locale) ? localizedMainPages[locale] : localizedMainPages[DefaultLocale];

            return result.Clone();
        }
    }
}